import React, { useRef, useEffect, useState } from 'react';
import { useParticleAnimation } from './ParticleAnimation';
import useRobotAnimation, { drawRobot } from './RobotAnimation';
import {
  INITIAL_PARTICLES,
  LOGIN_FORM_POSITION,
  ROBOT_SIZE,
  ENABLE_ROBOT
} from './constants';
import { Particle, ConnectionLine } from './types';
import './animation.css';

interface ParticleBackgroundProps {
  width?: number;
  height?: number;
  robotSize?: number;
  enableRobot?: boolean;
}

const ParticleBackground: React.FC<ParticleBackgroundProps> = ({
  width,
  height,
  robotSize = ROBOT_SIZE,
  enableRobot = ENABLE_ROBOT
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const formPositionRef = useRef<{x: number, y: number, width: number, height: number}>(LOGIN_FORM_POSITION);
  const animationFrameRef = useRef<number>(0);
  const mousePositionRef = useRef({x: 0, y: 0});
  const [isInitialized, setIsInitialized] = useState(false);
  
  // 获取粒子系统
  const {
    particlesRef,
    connectionPulsesRef,
    lastParticleCreationRef,
    performanceMetricsRef,
    lastPerformanceCheckRef,
    initParticles,
    checkPerformance,
    generateParticles,
    updateParticles,
    drawParticles,
    drawConnectionLines
  } = useParticleAnimation();
  
  // 获取机器人动画
  const { robotRef, updateRobot, drawRobot } = useRobotAnimation(robotSize);
  
  // 鼠标移动处理
  const handleMouseMove = (e: MouseEvent) => {
    if (!canvasRef.current) return;
    
    const rect = canvasRef.current.getBoundingClientRect();
    mousePositionRef.current = {
      x: e.clientX - rect.left,
      y: e.clientY - rect.top
    };
  };
  
  // 渲染场景
  const renderScene = (timestamp: number) => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    
    const ctx = canvas.getContext('2d');
    if (!ctx) return;
    
    // 检查性能并决定是否进入低性能模式
    const lowPerformanceMode = checkPerformance(timestamp);
    
    // 清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 生成新粒子
    generateParticles(canvas, particlesRef, lastParticleCreationRef, lowPerformanceMode);
    
    // 更新并绘制机器人（如果启用）
    if (enableRobot) {
      updateRobot(robotRef.current, canvas, formPositionRef);
    }
    
    // 更新粒子并获取连接线
    const connectionLines = updateParticles(canvas, particlesRef, connectionPulsesRef, robotRef);
    
    // 绘制粒子
    drawParticles(ctx, particlesRef, lowPerformanceMode);
    
    // 绘制连接线
    drawConnectionLines(ctx, connectionLines);
    
    // 绘制机器人（如果启用）
    if (enableRobot) {
      drawRobot(ctx, robotRef.current, lowPerformanceMode);
    }
    
    // 继续动画循环
    animationFrameRef.current = requestAnimationFrame(renderScene);
  };
  
  // 调整画布大小
  const updateCanvasSize = () => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    
    // 获取父元素尺寸
    const parentElement = canvas.parentElement;
    if (!parentElement) return;
    
    // 设置全屏尺寸
    canvas.width = parentElement.clientWidth;
    canvas.height = parentElement.clientHeight;
    
    console.log('Canvas size updated:', canvas.width, canvas.height);
  };
  
  // 初始化
  useEffect(() => {
    console.log('ParticleBackground - Initialize effect triggered');
    
    const canvas = canvasRef.current;
    if (!canvas) {
      console.log('No canvas element found');
      return;
    }
    
    console.log('Canvas element found, initializing...');
    
    // 更新画布尺寸
    updateCanvasSize();
    
    // 初始化粒子
    initParticles(canvas);
    
    // 设置初始机器人位置（如果启用）
    if (enableRobot) {
      robotRef.current.x = canvas.width * 0.8;
      robotRef.current.y = canvas.height * 0.2;
      robotRef.current.size = robotSize; // 设置自定义尺寸
    }
    
    // 添加事件监听器
    window.addEventListener('mousemove', handleMouseMove);
    window.addEventListener('resize', updateCanvasSize);
    
    console.log('Starting animation loop');
    // 开始动画循环
    animationFrameRef.current = requestAnimationFrame(renderScene);
    
    setIsInitialized(true);
    
    // 清理函数
    return () => {
      console.log('Cleaning up particle background');
      window.removeEventListener('mousemove', handleMouseMove);
      window.removeEventListener('resize', updateCanvasSize);
      cancelAnimationFrame(animationFrameRef.current);
    };
  }, []); // 移除依赖项，确保初始化效果只执行一次
  
  console.log('Rendering ParticleBackground component');
  
  return (
    <canvas
      ref={canvasRef}
      style={{
        position: 'absolute',
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        zIndex: 0,
      }}
    />
  );
};

export default ParticleBackground; 